package cn.sumpu.app.wlcity.web.mvc.seckill;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import cn.sumpu.app.wlcity.biz.SeckillBiz;
import cn.sumpu.app.wlcity.domain.Seckill;
import cn.sumpu.app.wlcity.domain.SeckillPhone;
import cn.sumpu.app.wlcity.domain.SeckillTime;
import cn.sumpu.app.wlcity.exception.AppBusinessException;
import cn.sumpu.app.wlcity.util.Common;
import cn.sumpu.app.wlcity.util.IdGenerator;
import cn.sumpu.app.wlcity.web.util.ImageUtil;
import cn.sumpu.app.wlcity.web.util.PictureUrl;

@Controller
public class SeckillController {

	private static Logger logger = LoggerFactory
			.getLogger(SeckillController.class);

	@Autowired
	private SeckillBiz seckillBiz;
    //查询秒杀活动
	@RequestMapping(value = "/seckillList.cms")
	public String seckillList(String seckillType,Integer page,HttpServletRequest request) throws AppBusinessException {
		List<Seckill> seckillList = null;
	
		try {   
			if (page == null)
				page = 1;
			if(seckillType==null){ 
				seckillType="01";
			}
			seckillList = seckillBiz.getSeckillList(page,seckillType);
			int count =seckillBiz.getSeckillListCount(seckillType);
			int pageSize=Common.PAGE_SIZE_SECKILL;
			int totalPage=(count+pageSize-1)/pageSize; 
			request.setAttribute("totalPage", totalPage);
			request.setAttribute("page", page);
			request.setAttribute("seckillList", seckillList); 
			request.setAttribute("seckillType", seckillType); 
		} catch (AppBusinessException e) {
			e.printStackTrace();
			if (logger.isErrorEnabled()) {
				logger.error("MVC failure.", e);
			}
		}
		if (null != seckillList && seckillList.size() > 0) {
			request.setAttribute("seckillList", seckillList);
		}
		return "cms/seckill/seckillList";
	}
	//查询秒杀活动参与的用户
	@RequestMapping(value = "/selectSeckillUser.cms")
	public String selectSeckillUserList(String seckillId,Integer pageUser,HttpServletRequest request) throws AppBusinessException {
		List<SeckillPhone> seckillPhoneList = null;
	
		try {  
			if (pageUser == null)
				pageUser = 1;
			seckillPhoneList = seckillBiz.getSeckillPhoneList(pageUser,seckillId);
			int count =seckillBiz.getSeckillPhoneListCount(seckillId);
			int pageSize=Common.PAGE_SIZE_SECKILL; 
			int totalPageUser=(count+pageSize-1)/pageSize; 
			request.setAttribute("totalPageUser", totalPageUser);
			request.setAttribute("pageUser", pageUser);
			request.setAttribute("seckillPhoneList", seckillPhoneList); 
			request.setAttribute("seckillId", seckillId); 
		} catch (AppBusinessException e) {
			e.printStackTrace();
			if (logger.isErrorEnabled()) {
				logger.error("MVC failure.", e);
			}
		}
		return "cms/seckill/seckillUser";
	}
	
	//添加秒杀信息
	@RequestMapping(value = "/submitSeckill.cms",method = RequestMethod.POST)
	public String addSecKillTime(String validateMsg,Boolean isDaily,String startDate,String endDate,String title,String buttonName, String seckillType,String picUrl,String seckillcontent,String secKillTimeList,HttpServletRequest request,HttpServletResponse response) throws IOException {
		Seckill seckill =new Seckill();
		//活动Id
		String identifierSeckill =IdGenerator.createIdentifier();	
		seckill.setIdentifier(identifierSeckill);
		seckill.setButtonName(buttonName);
		seckill.setTitle(title);
		seckill.setBody(seckillcontent);
		seckill.setPicUrl(picUrl);
		seckill.setSeckillType(seckillType);
		seckill.setStartDate(startDate);
		seckill.setEndDate(endDate);
		seckill.setIsDaily(isDaily);
		seckill.setValidateMsg(validateMsg);
		try { 
			seckillBiz.insertSeckill(seckill);
		} catch (Exception e1) {
			 
			e1.printStackTrace();
		}
		try {
			response.setContentType("text/plain; charset=utf-8");
			PrintWriter out = response.getWriter();
			JSONArray secKillArray = JSONArray.fromObject(secKillTimeList);
			for (Object object : secKillArray) {
				JSONObject jsonObj = JSONObject.fromObject(object);
				SeckillTime seckillTime = (SeckillTime) JSONObject.toBean(jsonObj,
						SeckillTime.class);
				//秒杀ID变化的
				String identifierSeckillTime = IdGenerator.createIdentifier();	
				seckillTime.setIdentifier(identifierSeckillTime);
				//活动ID不变
				seckillTime.setSeckillId(seckill.getIdentifier());
				seckillBiz.insertSeckillTime(seckillTime);
			} 
			out.print("success");
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	//删除秒杀信息
	@RequestMapping(value = "/deleteSeckill.cms")
	public String deleteSeckill(String seckillId,HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter pw = response.getWriter();
			seckillBiz.deleteSeckill(seckillId);
			seckillBiz.deleteSeckillTime(seckillId);
			pw.print("success"); 
			
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("MVC failure.", e);
			}
		}
		return null;
	}
	//更新页面
	@RequestMapping(value = "/updateSeckill.cms")
	public String updateSeckill(String seckillId,String seckillType,HttpServletRequest request,
			HttpServletResponse response) {
		try { 
			Seckill seckill =seckillBiz.selectSeckill(seckillId);
			seckillType=seckill.getSeckillType();
			if(seckill.getIsDaily()==true){  
				request.setAttribute("seckillType", seckillType);
				request.setAttribute("seckill", seckill);
				return "cms/seckill/updateDailySeckill";
			}else if(seckill.getIsDaily()==false){
				request.setAttribute("seckillType", seckillType);
				request.setAttribute("seckill", seckill);
				return "cms/seckill/updateSeckill";
			}
			
			
		} catch (Exception e) { 
			if (logger.isErrorEnabled()) {
				logger.error("MVC failure.", e);
			}
		}
		return null;
	}
	//上传图片
	@RequestMapping(value = "/seckillUploadImg.cms")
	public String seckillUploadImg(HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache"); 
			PrintWriter pw = response.getWriter();
			PictureUrl pictureUrl = ImageUtil.uploadImage(request, "seckill");  
			pw.print(JSONObject.fromObject(pictureUrl));
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("MVC failure.", e);
			}
		}
		return null;
	}
	//修改秒杀活动
	@RequestMapping(value = "/updateSeckillWeb.cms",method = RequestMethod.POST)
	public String updateSeckill(String validateMsg,String startDate,String endDate,String title,String identifier,String seckillType,String buttonName, String picUrl,String seckillcontentUpdate,String secKillTimeList,HttpServletRequest request,HttpServletResponse response) throws IOException {
		Seckill seckill =new Seckill();
		//活动Id
		seckill.setIdentifier(identifier);
		seckill.setButtonName(buttonName);
		seckill.setTitle(title);
		seckill.setBody(seckillcontentUpdate);
		seckill.setPicUrl(picUrl);
		seckill.setSeckillType(seckillType);
		seckill.setStartDate(startDate);
		seckill.setEndDate(endDate);
		seckill.setValidateMsg(validateMsg);
		try {
			seckillBiz.updateSeckill(seckill);
			//删除原来有的秒杀时间
			seckillBiz.deleteSeckillTime(identifier);
			
			response.setContentType("text/plain; charset=utf-8");
			PrintWriter out = response.getWriter();
			JSONArray secKillArray = JSONArray.fromObject(secKillTimeList);
			for (Object object : secKillArray) {
				JSONObject jsonObj = JSONObject.fromObject(object);
				SeckillTime seckillTime = (SeckillTime) JSONObject.toBean(jsonObj,
						SeckillTime.class);
				//秒杀ID变化的
				String identifierSeckillTime = IdGenerator.createIdentifier();	
				seckillTime.setIdentifier(identifierSeckillTime);
				//活动ID不变
				seckillTime.setSeckillId(seckill.getIdentifier());
				seckillBiz.insertSeckillTime(seckillTime);
			} 
			out.print("success");
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	//关闭秒杀活动
	@RequestMapping(value = "/closedSeckill.cms")
	public String closedSeckill(String seckillId,HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter pw = response.getWriter();
			Seckill seckill=new Seckill();
			seckill.setIdentifier(seckillId);
			seckill.setEnabled(false);
			seckillBiz.updateSeckill(seckill);
			pw.print("success"); 
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("MVC failure.", e);
			}
		} 
		return null;
	} 
	//加载添加新秒杀页面
	@RequestMapping(value = "/getNewSeckill.cms")
	public String getNewSeckill(HttpServletRequest request,
			HttpServletResponse response) { 
		return "cms/seckill/newSeckill";
	}
	//加载时间控件区分日常活动
	@RequestMapping(value = "/seckillSec.cms")
	public String seckillSec(HttpServletRequest request,
			HttpServletResponse response) {
		return "cms/seckill/seckillSec";
	}
	//加载时间控件区分日常活动
	@RequestMapping(value = "/seckillDateSec.cms")
	public String seckillDateSec(HttpServletRequest request,
			HttpServletResponse response) {
		return "cms/seckill/seckillDate";
	}
	

}
